package de.tudresden.st.cbse.servlet;

import java.io.IOException;

import javax.naming.NamingException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import de.tudresden.st.cbse.calendar.user.RemoteUserManager;
import de.tudresden.st.cbse.util.RemoteLookup;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    private static final long serialVersionUID = 4940122164654439006L;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    	RemoteUserManager userManager = null;
        try {
            userManager = RemoteLookup.getUserManager();
        } catch (NamingException e) {
            e.printStackTrace();
            return;
        }
        
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        if (email != null && password != null && userManager.authenticate(email, password)) {
            HttpSession session = req.getSession(true);
            session.setAttribute("currentSessionUser", email);
            resp.sendRedirect("calendar");
        } else {
            resp.sendRedirect("index.jsp");
        }
    }
}
